package com.chuangshu.chuangshuteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuangshu.chuangshuteam.config.BaseContext;
import com.chuangshu.chuangshuteam.dto.FileMetadataDto;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.FileInfo;
import com.chuangshu.chuangshuteam.mapper.FileInfoMapper;
import com.chuangshu.chuangshuteam.service.UploadFileService;
import com.chuangshu.chuangshuteam.util.File;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class UploadFileServiceImpl implements UploadFileService {
    @Autowired
    File uploadFile;
    @Autowired
    FileInfoMapper fileInfoMapper;
    @Override
    public Result upload(MultipartFile file) {
        String contentType = file.getContentType();
        if (!uploadFile.isAllowedFileType(contentType)) {
            return Result.fail("上传文件类型不支持");
        }
        String fileType = uploadFile.getFileType(contentType);
        if (fileType.equals("unknown")){
            return Result.fail("上传文件类型不支持");
        }
        byte[] bytes  = null;
        String url = "";
        try {
            bytes = file.getBytes();
             url = uploadFile.uploadFile(bytes, file.getOriginalFilename(), contentType, fileType);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        FileMetadataDto fileMetadataDto = new FileMetadataDto();
        fileMetadataDto.setFileSize(file.getSize());
        fileMetadataDto.setFilePath(url);
        fileMetadataDto.setFileType(fileType);
        fileMetadataDto.setFileName(file.getOriginalFilename());
        fileMetadataDto.setCreatedBy(BaseContext.getCurrentId());
        return Result.ok(fileMetadataDto);

    }

    @Override
    public Result uploadFiles(List<MultipartFile> files) {
        List<FileMetadataDto> fileMetadataDtos = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            String contentType = files.get(i).getContentType();
            String fileType = uploadFile.getFileType(contentType);
            byte[] bytes  = null;
            String url = "";
            try {
                bytes = files.get(i).getBytes();
                url = uploadFile.uploadFile(bytes, files.get(i).getOriginalFilename(), contentType, fileType);
                FileMetadataDto fileMetadataDto = new FileMetadataDto();
                fileMetadataDto.setFileSize(files.get(i).getSize());
                fileMetadataDto.setFilePath(url);
                fileMetadataDto.setFileType(fileType);
                fileMetadataDto.setFileName(files.get(i).getOriginalFilename());
                fileMetadataDto.setCreatedBy(BaseContext.getCurrentId());
                fileMetadataDtos.add(fileMetadataDto);
            } catch (Exception e) {
                log.error(e.getMessage());
                throw new RuntimeException(e);
            }
        }
        return Result.ok(fileMetadataDtos);
    }

    @Override
    public Result getFileListByBusinessIdAndType(Long businessId, String businessType) {
        log.info("查询文件列表，businessId: {}, businessType: {}", businessId, businessType);
        List<FileInfo> fileInfos = fileInfoMapper.selectByBusinessIdAndType(businessId, businessType);
        return Result.ok(fileInfos);
    }

    @Override
    public Result deleteFilesByBusinessIdAndType(Long businessId, String businessType) {
        log.info("删除文件，businessId: {}, businessType: {}", businessId, businessType);
        LambdaQueryWrapper<FileInfo> fileInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fileInfoLambdaQueryWrapper.eq(FileInfo::getBusinessId, businessId);
        fileInfoLambdaQueryWrapper.eq(FileInfo::getBusinessType, businessType);
        List<FileInfo> fileInfos = fileInfoMapper.selectList(fileInfoLambdaQueryWrapper);

        if (!fileInfos.isEmpty()){
            for (FileInfo fileInfo : fileInfos) {
                if (!Objects.equals(fileInfo.getCreatedBy(), BaseContext.getCurrentId())){
                    log.info("删除文件失败，文件创建者id: {}, 当前用户id: {}", fileInfo.getCreatedBy(), BaseContext.getCurrentId());
                    return Result.fail("不是自己创建的文件,删除文件失败");
                }
                uploadFile.deleteByUrl(fileInfo.getFilePath());
            }
        }else {
            log.info("没有找到文件");
            return Result.fail("没有找到文件");
        }
        int i = fileInfoMapper.deleteByBusinessIdAndType(businessId, businessType);
        return Result.ok("成功删除" + i + "个文件");
    }

    @Override
    public Result deleteFileById(Long fileId) {
        log.info("根据ID删除文件，fileId: {}", fileId);
        // 先查询文件信息
        FileInfo fileInfo = fileInfoMapper.selectById(fileId);
        if (fileInfo == null) {
            log.info("未找到ID为 {} 的文件", fileId);
            return Result.fail("未找到指定文件");
        }

        // 检查是否是当前用户上传的文件
        if (!Objects.equals(fileInfo.getCreatedBy(), BaseContext.getCurrentId())) {
            log.info("删除文件失败，文件创建者id: {}, 当前用户id: {}", fileInfo.getCreatedBy(), BaseContext.getCurrentId());
            return Result.fail("不是自己创建的文件，删除文件失败");
        }

        // 从数据库中删除记录
        int deletedCount = fileInfoMapper.deleteById(fileId);
        if (deletedCount > 0) {
            // 从存储中删除文件
            uploadFile.deleteByUrl(fileInfo.getFilePath());
            log.info("成功删除文件，fileId: {}", fileId);
            return Result.ok("文件删除成功");
        } else {
            log.info("删除文件失败，fileId: {}", fileId);
            return Result.fail("文件删除失败");
        }
    }
    @Override
    public Result getFileById(Long fileId) {
        log.info("根据ID查询文件详细信息，fileId: {}", fileId);
        // 查询文件信息
        FileInfo fileInfo = fileInfoMapper.selectById(fileId);
        if (fileInfo == null) {
            log.info("未找到ID为 {} 的文件", fileId);
            return Result.fail("未找到指定文件");
        }


        log.info("成功查询文件详细信息，fileId: {}", fileId);
        return Result.ok(fileInfo);
    }

    @Override
    public String getFileUrl(MultipartFile files) {
        String contentType = files.getContentType();
        String fileType = uploadFile.getFileType(contentType);
        String url = "";
        try {
            url = uploadFile.uploadFile(files.getBytes(), files.getOriginalFilename(), contentType, fileType);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return url;
    }
}
